package MongodbUtils

import (
	LogUtils "IMServices/LogService"
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type MongoClientInterface interface {
	StartMongoService(addr string, databaseName string)
	release()
	insertData(collName string, data interface{}) error
	updateData(collName string, key string, value string) error
	deleteData(collName string, id int64) error
	selectDataFromUserId(collName string, id int64)
	selectDataFromNotifyId(collName string, id int64)
}

type MongoClient struct {
	client   *mongo.Client
	database *mongo.Database
}

func (m *MongoClient) release() {
	// 断开MongoDB连接

	LogUtils.LogInfo("Connection closed.")
	err := m.client.Disconnect(context.Background())
	if err != nil {
		return
	}

}
func (m *MongoClient) insertData(collName string, data interface{}) error {
	collection := m.database.Collection(collName)
	// 插入数据
	person := Person{Name: "John", Age: 30, Email: "john@example.com"}
	insertResult, err := collection.InsertOne(context.Background(), person)
	if err != nil {
		LogUtils.LogError(err)
	}
	LogUtils.LogInfo("Inserted person with ID:", insertResult.InsertedID)
	return err
}
func (m *MongoClient) updateData(collName string, key string, value string) error {
	collection := m.database.Collection(collName)
	// 更新数据
	filter := bson.M{"name": "John"}
	update := bson.M{"$set": bson.M{"age": 40}}
	updateResult, err := collection.UpdateOne(context.Background(), filter, update)
	if err != nil {
		LogUtils.LogError(err)
	}
	LogUtils.LogInfo("Updated %v documents\n", updateResult.ModifiedCount)
	return err
}
func (m *MongoClient) deleteData(collName string, id int64) error {
	collection := m.database.Collection(collName)
	filter := bson.M{"name": "John"}
	// 删除数据
	deleteResult, err := collection.DeleteOne(context.Background(), filter)
	if err != nil {
		LogUtils.LogError(err)
	}
	LogUtils.LogInfo("Deleted %v documents\n", deleteResult.DeletedCount)
	return err
}
func (m *MongoClient) selectDataFromUserId(collName string, id int64) {
	collection := m.database.Collection(collName)
	// 查询数据
	filter := bson.M{"name": "John"}
	var result Person
	err := collection.FindOne(context.Background(), filter).Decode(&result)
	if err != nil {
		LogUtils.LogError(err)
	}
	LogUtils.LogInfo("Found person:", result)

}
func (m *MongoClient) selectDataFromNotifyId(collName string, id int64) {

}

func (m *MongoClient) StartMongoService(addr string, databaseName string) {
	// 建立MongoDB连接
	//errorMongo := errors.New("")
	var errorMongo error
	clientOptions := options.Client().ApplyURI(addr)
	m.client, errorMongo = mongo.Connect(context.Background(), clientOptions)
	if errorMongo != nil {
		LogUtils.LogError(errorMongo)
	}

	// 指定数据库和集合
	m.database = m.client.Database(databaseName) //.Collection("persons")

}
